import { CMEVENTS } from '@amcax/base';
import { userEvents } from '@app-cad/module';
import {
  DeleteOutlined,
  ImportOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import { cmdComponentImport } from '@app-cad-env/nextcad/commands/feature/cmd-component-import';
import { httpApi } from '@app-cad/server';
import {
  Button,
  Card,
  Col,
  Dropdown,
  Empty,
  Input,
  Modal,
  Popconfirm,
  Row,
  Select,
  Space,
  Tabs,
  Tag,
  Tooltip,
  Typography,
} from 'antd';
import { debounce } from 'lodash';
import React, { useEffect, useRef, useState } from 'react';
import { BsBadge3DFill } from 'react-icons/bs';
import styled from 'styled-components';

const { Title } = Typography;

const StyledCoverView = styled.div`
  position: relative;
  img {
    height: 150px;
    width: 100%;
  }
  .ant-btn {
    position: absolute;
    right: 0px;
    top: 0px;
  }
`;
const StyledCardView = styled(Card)`
  .ant-card-cover {
    margin: 0;
  }
  .ant-card-body {
    padding: 10px;
  }
  .ant-card-meta-title {
    margin-bottom: 5px;
  }
  .ant-card-actions > li {
    margin: 0;
  }
`;

const tabItems = [
  {
    label: '我的',
    key: 'personal',
  },
  {
    label: '公共',
    key: 'public',
  },
  {
    label: '全部',
    key: 'all',
  },
];
export default function ComponentPanel() {
  const width = 390;
  const [keyword, setKeyword] = useState('');
  const [category, setCategory] = useState('all');
  const [source, setSource] = useState('personal');
  const [page, setPage] = useState(1);
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [pageSize, setPageSize] = useState(10);
  const [hasMore, setHasMore] = useState(true);
  const [categories, setCategories] = React.useState<any[]>([]);
  const [components, setComponents] = useState<any[]>([]);
  const componentItem = useRef<any>(null);

  const categoryMap = useRef<Map<string, string>>();

  useEffect(() => {
    loadCategories();
    userEvents.emit(CMEVENTS.RIGHT_PANEL_TOGGLE, { open: true, width });
    return () => {
      userEvents.emit(CMEVENTS.RIGHT_PANEL_TOGGLE, { open: false, width });
    };
  }, []);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [nameVal, setNameVal] = useState('');
  useEffect(() => {
    registerEvents();
    searchComponents();
  }, [keyword, category, source, page]);

  const registerEvents = () => {
    userEvents.on(CMEVENTS.COMPONENT_ADDED, () => {
      searchComponents();
    });
  };

  const handleKeywordChange = (value: string) => {
    handleSearchDebounce(value);
  };
  const handleSearchDebounce = debounce((value: string) => {
    setKeyword(value);
  }, 1000);

  const handleCategoryChange = (value: string) => {
    setCategory(value);
  };

  const loadCategories = async () => {
    const { data } = await httpApi.getComponentCategories();
    const categories = [{ id: 'all', name: '全部' }, ...data];
    categoryMap.current = new Map(
      categories.map((item) => [item.id, item.name]),
    );
    setCategories(categories);
  };
  const searchComponents = async () => {
    const params = {
      page,
      pageSize,
    };
    if (source != 'all') {
      params['source'] = source;
    }
    if (category != 'all') {
      params['category'] = category;
    }
    if (keyword) {
      params['keyword'] = keyword;
    }
    const { data } = await httpApi.getComponents(params);
    console.log('result', data);
    setHasMore(data.hasMore);
    if (data.list) {
      if (page === 1) {
        setComponents(data.list);
      } else {
        setComponents([...components, ...data.list]);
      }
    } else {
      setComponents([]);
    }
  };

  const handleComponentDelete = async (uuid: string) => {
    await httpApi.deleteComponent(uuid);
    searchComponents();
  };

  const handleComponentPreview = (component: any) => {
    userEvents.emit(CMEVENTS.COMPONENT_PREVIEW, { url: component.preview3D });
  };
  const handleComponentImport = (component: any) => {
    console.log('handleComponentImport', component);
    const { s3Location } = component;
    cmdComponentImport.invoke({ gallery: s3Location });
  };

  const loadMore = () => {
    if (hasMore) {
      setPage(page + 1);
    }
  };

  const SearchBar = () => {
    return (
      <>
        <Space.Compact
          direction='horizontal'
          block
          style={{ marginTop: '0px', marginBottom: '15px' }}>
          <Input
            placeholder='搜索关键字'
            style={{ width: '60%' }}
            value={keyword}
            onChange={(e) => handleKeywordChange(e.target.value)}
          />
          <Select
            placeholder='构件类型'
            style={{ width: '40%' }}
            value={category}
            onChange={handleCategoryChange}
            options={categories.map((item: any) => {
              return {
                value: item.id,
                label: item.name,
              };
            })}
          />
        </Space.Compact>
        {/* COMMON 通用、BIM 建筑、ELECTRIC 电力、TRAFFIC 道路交通、MACHINE 机械 */}
      </>
    );
  };

  const CoverView = ({ component }) => {
    return (
      <StyledCoverView>
        {component.preview3D !== '' ? (
          <Tooltip title='3D预览'>
            <Button
              type='text'
              size='large'
              icon={<BsBadge3DFill />}
              onClick={() => handleComponentPreview(component)}
            />
          </Tooltip>
        ) : null}
        <img src={component.thumbnail} />
      </StyledCoverView>
    );
  };
  const inputing = (e) => {
    const name = e.target.value as string;
    setNameVal(name);
  };

  const Components = () => {
    return (
      <div style={{ width: '100%', overflowY: 'auto', overflowX: 'hidden' }}>
        {components.length > 0 ? (
          <>
            <Row gutter={[16, 16]}>
              {components.map((component, index) => {
                return (
                  <Col
                    span={12}
                    key={index}>
                    <StyledCardView
                      cover={<CoverView component={component} />}
                      actions={
                        component.visibility === 'public'
                          ? [
                              <Button
                                type='text'
                                color='primary'
                                icon={<ImportOutlined />}
                                onClick={() =>
                                  handleComponentImport(component)
                                }>
                                导入
                              </Button>,
                            ]
                          : [
                              <Button
                                type='text'
                                color='primary'
                                icon={<ImportOutlined />}
                                onClick={() =>
                                  handleComponentImport(component)
                                }>
                                导入
                              </Button>,
                              <Popconfirm
                                title='是否确定删除该构件？'
                                icon={<QuestionCircleOutlined />}
                                okText='确定'
                                cancelText='取消'
                                onConfirm={() =>
                                  handleComponentDelete(component.uuid)
                                }>
                                <Button
                                  type='text'
                                  icon={<DeleteOutlined />}
                                  danger>
                                  删除
                                </Button>
                              </Popconfirm>,
                            ]
                      }>
                      <Card.Meta
                        title={
                          <div style={{ display: 'flex' }}>
                            <span style={{ flex: 1 }}>{component.name}</span>
                            {source === 'personal' && (
                              <Dropdown
                                menu={{
                                  items: [
                                    {
                                      key: '1',
                                      label: (
                                        <a
                                          rel='noopener noreferrer'
                                          onClick={() => {
                                            setIsModalOpen(true);
                                            componentItem.current = component;
                                            setNameVal(component.name);
                                          }}>
                                          修改名称
                                        </a>
                                      ),
                                    },
                                    {
                                      key: '2',
                                      label: (
                                        <Popconfirm
                                          title='是否确定设置为公共构件库？'
                                          icon={<QuestionCircleOutlined />}
                                          okText='确定'
                                          cancelText='取消'
                                          onConfirm={() => {
                                            updateComponent({
                                              visibility: 'public',
                                            });
                                          }}>
                                          <a
                                            rel='noopener noreferrer'
                                            onClick={() => {
                                              componentItem.current = component;
                                            }}>
                                            设置公共
                                          </a>
                                        </Popconfirm>
                                      ),
                                    },
                                  ].slice(
                                    0,
                                    component.visibility.includes('public')
                                      ? 1
                                      : 2,
                                  ),
                                }}
                                placement='bottomLeft'
                                arrow>
                                <Tag
                                  style={{ color: '#000', cursor: 'pointer' }}
                                  color='info'>
                                  操作
                                </Tag>
                              </Dropdown>
                            )}
                          </div>
                        }
                        description={
                          <Space size={1}>
                            <Tag color='default'>
                              {categoryMap.current &&
                                categoryMap.current.get(component.category)}
                            </Tag>
                            {component.visibility === 'public' ? (
                              <Tag color='success'>公用</Tag>
                            ) : (
                              <Tag color='warning'>个人</Tag>
                            )}
                          </Space>
                        }
                      />
                    </StyledCardView>
                  </Col>
                );
              })}
            </Row>
            {hasMore ? (
              <Button
                type='default'
                block
                style={{ marginTop: '10px' }}
                onClick={loadMore}>
                加载更多...
              </Button>
            ) : null}
          </>
        ) : (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description='暂无数据'
          />
        )}
      </div>
    );
  };

  const handleTabChange = (key: string) => {
    setPage(1);
    setSource(key);
  };
  // 更新组件
  const updateComponent = async (params) => {
    const documentId = window.location.search
      .slice(1)
      .split('&')
      .find((item) => item.includes('doc='))
      .split('=')[1];
    const param = {
      uuid: componentItem?.current.uuid,
      projectUUID: documentId,
      category: componentItem.current.category,
      visibility: componentItem.current.visibility,
      name: componentItem.current.name,
      ...params,
    };
    let flag = true;
    if (params.name) {
      const res = await httpApi.checkComponentName({
        name: param.name,
        category: param.category,
      });
      flag = res?.data?.available;
    }
    flag &&
      httpApi.updateComponent(param).then(() => {
        setIsModalOpen(false);
        componentItem.current.name = param.name;
        componentItem.current.visibility = param.visibility;
      });
  };
  useEffect(() => {
    console.log('componentItem', componentItem);
  }, [componentItem]);

  return (
    <div
      style={{
        padding: '20px',
        display: 'flex',
        flexDirection: 'column',
        width: width + 'px',
        height: '100%',
      }}>
      <Title level={4}>构件库</Title>
      <Tabs
        defaultActiveKey={source}
        onChange={handleTabChange}
        items={tabItems}
      />
      <SearchBar />
      <Components />

      <Modal
        title='修改名称'
        okText='确定'
        cancelText='取消'
        open={isModalOpen}
        onOk={() => {
          updateComponent({ name: nameVal });
        }}
        onCancel={() => {
          setIsModalOpen(false);
        }}>
        <Input
          value={nameVal}
          onChange={inputing}></Input>
      </Modal>
    </div>
  );
}
